import React from 'react'
import { Upload, Button, message } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { awaitWrap } from '@js/tool'
import { $post } from '@js/request'
import style from './Index.module.less'
import ImgCrop from 'antd-img-crop'
import FileList from '@components/FileList/Index'

// 上传单个文件请求
export const requestOneFile = async function (file) {
  const config = {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }
  const formData = new FormData()
  formData.append('upload_file', file)
  const res = await $post('/api/common/upload', formData, config)
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

// 上传多个文件请求
async function requestFiles (files) {
  const list = files.map(requestOneFile)
  return await Promise.all(list)
}

function getUploadProps (accept, fileList, setFileList) {
  const o = {
    onRemove: (file) => {
      const index = fileList.indexOf(file)
      const newFileList = fileList.slice()
      newFileList.splice(index, 1)
      setFileList(newFileList)
    },
    beforeUpload: (file) => {
      if (accept !== undefined) {
        const arr = accept.split(',')
        const i = file.name.lastIndexOf('.')
        const n = file.name.slice(i)
        if (!arr.includes(n)) {
          message.warning(`文件格式不符，文件格式必须为${accept}`)
          return false
        }
      }
      const f = { originFileObj: file, name: file.name, filename: file.name, id: '', url: '', original_filename: '', path: '' }
      const l = [...fileList, f]
      setFileList(l)
      return false
    },
    fileList
  }
  if (accept !== undefined) {
    o.accept = accept
  }
  return o
}

async function uploadsRequst (files) {
  const arr = await requestFiles(files)
  return arr
}

export async function uploadFile (fileList) {
  let uploaded = []
  const files = []
  fileList.forEach(li => {
    if (li instanceof File) {
      files.push(li)
    } else if (li.originFileObj instanceof File) {
      files.push(li.originFileObj)
    } else {
      uploaded.push(li)
    }
  })
  if (files.length > 0) {
    const hide = message.loading('上传中')
    const [e, d] = await awaitWrap(uploadsRequst(files))
    hide()
    if (e !== null) {
      return []
    }
    if (d === null) {
      message.error('数据没有返回').then(null, null)
    } else {
      uploaded = uploaded.concat(d.map((li, i) => {
        const file = files[i]
        return {
          ...li,
          original_filename: file.name,
          path: li.url
        }
      }))
    }
  }
  return uploaded
}

function Main ({ value = [], accept, maxLength, image = false, placeholder, aspect = 1, readonly = false, onChange = () => {} }) {
  if (image) {
    return (
      <ImgCrop rotate aspect={aspect}>
        <Upload listType='picture-card' {...getUploadProps(accept, value, onChange)}>
          {typeof maxLength === 'number' && value.length >= maxLength ? '' : <div className={style['upload-icon']}><UploadOutlined /></div>}
        </Upload>
      </ImgCrop>
    )
  }
  const remarks = []
  if (accept !== undefined) {
    remarks.push(`支持扩展名：${accept}`)
  }
  if (placeholder !== undefined) {
    remarks.push(placeholder)
  }
  if (readonly) {
    return (
      <div className={style.container}>
        <FileList value={value} />
      </div>
    )
  }
  return (
    <div className={style.container}>
      <Upload {...getUploadProps(accept, value, onChange)}>
        <Button disabled={typeof maxLength === 'number' && value.length >= maxLength}>
          <UploadOutlined /> 上传文件
        </Button>
      </Upload>
      <div className={style.submessage}>{remarks.join('，')}</div>
    </div>
  )
}

export default Main
